#include <jni.h>
#include <string>
#include "EnjoyPlayer.h"
#include "JavaCallHelper.h"

extern "C" {
#include "libavutil/avutil.h"
}

// 子线程需要调用主线程的时候就会涉及到JavaVm
JavaVM *javaVm = nullptr;


JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    javaVm = vm;
    return JNI_VERSION_1_4;
}


extern "C"
JNIEXPORT jlong JNICALL
Java_per_zhou_testffmpeg_EnjoyPlayer_nativeInit(JNIEnv *env, jobject thiz) {
    // jobject thiz 代表Java实例对象EnjoyPlayer
    EnjoyPlayer *player = new EnjoyPlayer(new JavaCallHelper(javaVm, env, thiz));
    return reinterpret_cast<jlong>(player);
}



extern "C"
JNIEXPORT void JNICALL
Java_per_zhou_testffmpeg_EnjoyPlayer_prepare(JNIEnv *env, jobject thiz, jlong native_handle) {
    EnjoyPlayer *player = reinterpret_cast<EnjoyPlayer *>(native_handle);
    player->prepare();

}
extern "C"
JNIEXPORT void JNICALL
Java_per_zhou_testffmpeg_EnjoyPlayer_setDataSource(JNIEnv *env, jobject thiz, jlong native_handle, jstring path_) {

    const char *path = env->GetStringUTFChars(path_, 0);

    EnjoyPlayer *player = reinterpret_cast<EnjoyPlayer *>(native_handle);

    player->setDataSource(path);
    env->ReleaseStringChars(path_, reinterpret_cast<const jchar *>(path));
}


extern "C"
JNIEXPORT void JNICALL
Java_per_zhou_testffmpeg_EnjoyPlayer_start(JNIEnv *env, jobject thiz, jlong native_handle) {
    EnjoyPlayer *player = reinterpret_cast<EnjoyPlayer *>(native_handle);
    player->start();


}



extern "C"
JNIEXPORT void JNICALL
Java_per_zhou_testffmpeg_EnjoyPlayer_setSurface(JNIEnv *env, jobject thiz, jlong native_handle, jobject surface) {

    EnjoyPlayer *player = reinterpret_cast<EnjoyPlayer *>(native_handle);
    ANativeWindow *window = ANativeWindow_fromSurface(env, surface);
    player->setWindow(window);

}